package com.example.demo.utils.http;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class HttpClientUtil {

	/**
	 * 以JSON格式的方式发送POST请求
	 *
	 * @param url        URL地址
	 * @param jsonParams 请求参数
	 *
	 * @return
	 *
	 * @throws RuntimeException
	 */
	public static String POST(String url, String jsonParams) throws RuntimeException {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		CloseableHttpResponse response = null;

		HttpPost httppost = new HttpPost(url);
		try {
			httppost.addHeader(HTTP.CONTENT_TYPE, "application/json");

			if (StringUtils.isNotBlank(jsonParams)) {
				// 解决中文乱码问题
				StringEntity entity = new StringEntity(jsonParams, "UTF-8");
				entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
				entity.setContentType("application/json");
				httppost.setEntity(entity);
			}

			response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			return EntityUtils.toString(entity, "UTF-8");
		} catch (Exception e) {
			throw new RuntimeException("发送HTTP POST请求失败：" + e.getMessage(), e);
		} finally {
			if (response != null) {
				try {
					response.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 发送POST请求
	 *
	 * @param url：URL地址
	 * @param params：请求参数
	 * @param headers：请求头内容
	 * @param charset：编码
	 *
	 * @return
	 *
	 * @throws RuntimeException
	 */
	public static String POST(String url, Map<String, String> params, Map<String, String> headers, String charset) throws RuntimeException {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		HttpPost httppost = new HttpPost(url);

		CloseableHttpResponse response = null;
		//参数
		List<NameValuePair> formparams = new ArrayList<NameValuePair>();
		if (params != null && ! params.isEmpty()) {
			Iterator<Map.Entry<String, String>> iterator = params.entrySet().iterator();
			while (iterator.hasNext()) {
				Map.Entry<String, String> entity = iterator.next();
				formparams.add(new BasicNameValuePair(entity.getKey(), entity.getValue()));
			}
		}

		try {
			UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(formparams, charset);
			httppost.setEntity(urlEncodedFormEntity);
			if (headers != null && ! headers.isEmpty()) {
				Iterator<Map.Entry<String, String>> iterator = headers.entrySet().iterator();
				while (iterator.hasNext()) {
					Map.Entry<String, String> entity = iterator.next();
					httppost.setHeader(entity.getKey(), entity.getValue());
				}
			}

			response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			return EntityUtils.toString(entity, charset);
		} catch (Exception e) {
			throw new RuntimeException("发送HTTP POST请求失败：" + e.getMessage(), e);
		} finally {
			if (response != null) {
				try {
					response.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 发送POST请求
	 *
	 * @param url：URL地址
	 * @param params：请求参数
	 * @param charset：编码
	 *
	 * @return
	 *
	 * @throws RuntimeException
	 */
	public static String POST(String url, Map<String, String> params, String charset) throws RuntimeException {
		return POST(url, params, null, charset);
	}

	/**
	 * 发送POST请求
	 *
	 * @param url：请求地址
	 * @param params：请求参数
	 *
	 * @return
	 *
	 * @throws RuntimeException
	 */
	public static String POST(String url, Map<String, String> params) throws RuntimeException {
		return POST(url, params, null, "UTF-8");
	}

	/**
	 * 发送GET请求
	 *
	 * @param url：请求地址
	 *
	 * @return
	 */
	public static String GET(String url) {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpGet get = new HttpGet(url);
		CloseableHttpResponse httpResponse = null;
		try {
			httpResponse = httpClient.execute(get);
			HttpEntity entity = httpResponse.getEntity();
			if (entity != null && httpResponse.getStatusLine().getStatusCode() == 200) {
				return EntityUtils.toString(entity);
			} else {
				throw new RuntimeException("发送GET请求失败");
			}
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage(), e);
		} finally {
			if (httpResponse != null) {
				try {
					httpResponse.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 发送GET请求，加Cookie信息
	 *
	 * @param url：请求地址
	 *
	 * @return
	 */
	public static String GET(String url, String cookies) {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpGet get = new HttpGet(url);
		get.setHeader("Connection", "keep-alive");
		get.addHeader(new BasicHeader("Cookie", cookies));
		CloseableHttpResponse httpResponse = null;
		try {
			httpResponse = httpClient.execute(get);
			HttpEntity entity = httpResponse.getEntity();
			if (entity != null && httpResponse.getStatusLine().getStatusCode() == 200) {
				return EntityUtils.toString(entity);
			} else {
				throw new RuntimeException("发送GET请求失败");
			}
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage(), e);
		} finally {
			if (httpResponse != null) {
				try {
					httpResponse.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

}

